package com.itheima.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Code;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Log4j2
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 验证码
     * @param user
     * @return
     */
    @Override
    public Result sendMsg(User user) {
        //判断redis是否已经有该号码 验证码
        Object o = redisTemplate.opsForValue().get(user.getPhone());
        if (o == null){
        //    不存在验证码 查询redis是否有该用户的信息
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", user.getPhone());
            List user1 = userMapper.selectList(wrapper);
            //如果没有就往redis新建这个用户信息
            if (user1.size() == 0 ){
                User user2 = new User();
                user2.setPhone(user.getPhone());
                user2.setStatus(1);
                userMapper.insert(user2);
            }
        }
        //redis有用户信息 生成六位随机数
        String code = RandomUtil.randomNumbers(6);
        //把随机数放到redis
        redisTemplate.opsForValue().set(user.getPhone(), code,60, TimeUnit.SECONDS);
        return new Result(null, "手机验证码发送成功", "{}");
    }

    /**
     * 登录
     * @param
     * @return
     */
    @Override
    public Result login(User user) {
        //获取该号码的验证码
        Object o = redisTemplate.opsForValue().get(user.getPhone());
        //判断验证码跟redis的验证码是否相同
        if (user.getCode().equals(o)){
            // 生成token
            String s = user.getPhone() + System.currentTimeMillis();
        //    保存token到数据库
            redisTemplate.opsForValue().set(s, user.getPhone(),1,TimeUnit.DAYS);
            // 查看该手机在数据库里的数据
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", user.getPhone());
            List<User> one = userMapper.selectList(wrapper);
            //放到集合返回给前端
            User user1 = new User();
            for (User o1 : one) {
                user1.setId(o1.getId());
                user1.setToken(s);
                user1.setPhone(o1.getPhone());
                user1.setStatus(o1.getStatus());
            }

            return new Result(Code.OK, user1, "{}");
        }
        return new Result(Code.ERR401,"",  "{}");
    }
}
